﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace AMatysiak.Methods
{
    public static class DateExtensions
    {
        public static int GetMonthsBetween(this DateTime dt1, DateTime dt2)
        {
            if (WrongSequenceOfDates(ref dt1, ref dt2))
                SwapDates(ref dt1, ref dt2);

            return CalculateMonths(dt1, dt2);
        }

        private static bool WrongSequenceOfDates(ref DateTime dt1, ref DateTime dt2)
        {
            return dt1 < dt2;
        }

        private static void SwapDates(ref DateTime dt1, ref DateTime dt2)
        {
            DateTime dt3 = dt1;
            dt1 = dt2;
            dt2 = dt3;
        }

        private static int CalculateMonths(DateTime dt1, DateTime dt2)
        {
            return CalculateMonthsByDays(dt1, dt2) + 
                CalculateMonthsByMonths(dt1, dt2) +
                CalculateMonthsByYears(dt1, dt2);
        }

        private static int CalculateMonthsByDays(DateTime dt1, DateTime dt2)
        {
            return dt1.Day >= dt2.Day ? 0 : -1;
        }

        private static int CalculateMonthsByMonths(DateTime dt1, DateTime dt2)
        {
            return (dt1.Year - dt2.Year) * 12;
        }

        private static int CalculateMonthsByYears(DateTime dt1, DateTime dt2)
        {
            return dt1.Month - dt2.Month;
        }

        public static string WithoutSeconds(this DateTime dt)
        {
            return dt.ToString().Substr(-3);
        }

        public static string ToDate(this DateTime dt)
        {
            return dt.ToShortDateString();
        }

        public static string ToTime(this DateTime dt)
        {
            return dt.ToShortTimeString();
        }

        public static string MonthPolishName(this DateTime dt)
        {
            List<string> months = new List<string>(12)
            {
                "styczeń",
                "luty",
                "marzec",
                "kwiecień",
                "maj",
                "czerwiec",
                "lipiec",
                "sierpień",
                "wrzesień",
                "październik",
                "listopad",
                "grudzień"
            };

            return months[dt.Month - 1];
        }

        public static DateTime LastDayOfMonth(this DateTime dt)
        {
            return DateTime.Parse("{0}-{1}-{2}".FormatWith(
                dt.Year, dt.Month, DateTime.DaysInMonth(dt.Year, dt.Month)));
        }
    }
}
